<?php 
// +----------------------------------------------------------------------
// | Item
// +----------------------------------------------------------------------
// | Copyright
// +----------------------------------------------------------------------
// | Versions
// +----------------------------------------------------------------------
// | Author       YanHao
// +----------------------------------------------------------------------
// | Date         2017-07-03
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Controller;
use think\Session;
use think\Loader;

class Login extends Controller
{
    private static $_token_name    = 'flash_login_name';  
    private static $_session_uid   = 'uid';
    private static $_session_uinfo = 'b_uinfo';

    /**
     * 初始化
     * @return [type] [description]
     */
    public function _initialize()
    {
        Session::init();
    }

    /**
     * 首页
     * @return [type] [description]
     */
    public function index()
    {
        $token = md5($this->request->server('REQUEST_TIME_FLOAT'));
        Session::set(self::$_token_name,$token);
        $error = Session::pull('login_error');
        return $this->fetch('', ['token' => $token, 'error' => $error]);
    }
    /**
     * 登录
     * @return [type] [description]
     */
    public function login()
    {
        $post = $this->request->post(); //登录请求数据
        //验证Token
        if (!isset($post['__token__']) || ($post['__token__'] != Session::pull(self::$_token_name))) {
            Session::flash('login_error', '非法请求'); //下次请求生效
            $this->redirect('index');
        } else {
            $checkRes = Loader::model('Admin')->loginCheck($post, $this->request->ip(true));
            if ($checkRes['code']) {
                $info = $checkRes['data']['info'];
                Session::set(self::$_session_uid, $info['id']);
                $info['login_times'] += 1; //登陆次数
                $info['line_status'] = 1; //管理员在线状态
                Session::set(self::$_session_uinfo, $info);
                (new \app\admin\controller\Base) ->refreshSession(); 
                $this->redirect('Index/index'); 
            } else {
                Session::flash('login_error', $checkRes['data']['msg']);
                $this->redirect('index');
            }
        }

    }
    /**
     * 退出登录
     * @Author  YanHao
     * @Date    2017-07-05
     * @version [version]
     * @return  [type]         [description]
     */
    public function logout()
    {
        Loader::model('Admin')->changeStatus(Session::pull(self::$_session_uid), 0); //更改管理员状态为离线状态
        Session::clear();
        return $this->redirect('index');
    }

}